package controller

import (
	"class_bff/class"
	"class_bff/pkg"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
	"strconv"
	"time"
)

// 上传图片并发布
func ReleaseClass(c *gin.Context) {
	title := c.PostForm("title")
	isPay := c.PostForm("is_pay")
	IsPay, _ := strconv.Atoi(isPay)
	userId := c.PostForm("user_id")
	UserId, _ := strconv.Atoi(userId)
	typeId := c.PostForm("type_id")
	TypeId, _ := strconv.Atoi(typeId)
	comment := c.PostForm("comment")
	Comment, _ := strconv.Atoi(comment)
	if title == "" || isPay == "" || userId == "" || typeId == "" || comment == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "参数不能为空",
			"data": nil,
		})
		return
	}
	file, m, err := c.Request.FormFile("img")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "图片不能为空",
			"data": nil,
		})
		return
	}
	if m.Size > 10*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "文件过大,请上传小于10MB的文件",
			"data": nil,
		})
		return
	}
	ext := path.Ext(m.Filename)
	if ext != ".png" && ext != ".jpg" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "文件格式错误,请上传后缀为.png或.jpg的文件",
			"data": nil,
		})
		return
	}
	filename := "upload/" + time.Now().Format("20060102150405") + ext
	upload := pkg.Upload(filename, file)
	//远程连接class_rpc
	client := pkg.Comment()
	_, err = client.ReleaseClass(context.Background(), &class.ReleaseClassRequest{
		Title:   title,
		Img:     upload,
		IsPay:   int64(IsPay),
		UserId:  int64(UserId),
		TypeId:  int64(TypeId),
		Comment: int64(Comment),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "发布课程失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "发布课程成功",
		"data": nil,
	})
	return
}
